#include "chat.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QDialog>
#include <QListWidget>
#include <QMessageBox>
#include <QHostAddress>

Chat::Chat(const char * ip, const char * port) :
QDialog(NULL), m_socket(new QUdpSocket())
{
    if (!m_socket->bind(QHostAddress(ip), atoi(port)))
//    if (!m_socket->bind(QHostAddress::LocalHost, atoi(port)))
    {
        char str[300];
        sprintf(str, "Couldn't bind socket on ip %s, port %s", ip, port);
        QMessageBox::information(this, "error", str);
    }
    QVBoxLayout *vlay = new QVBoxLayout();
    QHBoxLayout *hlay1 = new QHBoxLayout();
    QHBoxLayout *hlay2 = new QHBoxLayout();
    m_listwidget = new QListWidget(this);
    vlay->addWidget(m_listwidget);
    hlay1->addWidget(new QLabel("IP address:", this));
    m_ipedit = new QLineEdit("127.0.0.1", this);
    hlay1->addWidget(m_ipedit);
    hlay1->addWidget(new QLabel("Port:", this));
    m_portedit = new QLineEdit("10005", this);
    hlay1->addWidget(m_portedit);
    vlay->addLayout(hlay1);
    hlay2->addWidget(new QLabel("Enter text:", this));
    m_textedit = new QLineEdit("Hello!", this);
    hlay2->addWidget(m_textedit);
    m_button = new QPushButton("Send", this);
    hlay2->addWidget(m_button);
    vlay->addLayout(hlay2);
    setLayout(vlay);

    connect(m_button, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(readMessage()));
}

void Chat::sendMessage()
{
    QByteArray data;
    data.append(m_textedit->text());
    m_socket->writeDatagram(data, QHostAddress(m_ipedit->text()), m_portedit->text().toUInt());
    QString d(data);
    d.push_front(">>> ");
    m_listwidget->addItem(d);
}

void Chat::readMessage()
{
    while (m_socket->hasPendingDatagrams())
    {
        QByteArray data;
        quint64 maxlen = m_socket->pendingDatagramSize();
        data.resize(maxlen);
        QHostAddress host;
        quint16 port;
        m_socket->readDatagram(data.data(), maxlen, &host, &port);
        QString d(data);
        d.push_front("<<< ");
        m_listwidget->addItem(d);
    }
}
